package com.wyix.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangdx
 * @since 2025/8/5
 */
@WebFilter(urlPatterns = {"/index.jsp", "/admin/*"}) // 保护的资源
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 检查Session中的登录状态
        if (req.getSession().getAttribute("loginUser") == null) {
            // 未登录，重定向到登录页
            resp.sendRedirect(req.getContextPath() + "/login.jsp?redirect=" + req.getRequestURI());
        } else {
            // 已登录，继续访问
            chain.doFilter(request, response);
        }
    }
}